<template>
  <map
    id="map"
    :longitude="userStore.longitude"
    :latitude="userStore.latitude"
    @markertap="handleMarkerTap"
  />

  <view class="footer">
    <button type="primary" @click="handleJump">发布</button>
  </view>
</template>

<script lang="ts" setup>
import { onLoad } from "@dcloudio/uni-app";
import { useUserStore } from "@/stores/user";

const userStore = useUserStore();
let mapCtx: UniApp.MapContext | null = null;

// 获取数据
const refresh = async () => {
  const { data } = await uni.request({
    url: "http://127.0.0.1:3000/trades",
    method: "GET",
  });

  // 添加标注点
  mapCtx?.addMarkers({
    clear: true,
    markers: (data as API.Trade[]).map((item) => ({
      id: item.id,
      longitude: item.lng,
      latitude: item.lat,
      width: 40,
      height: 40,
      iconPath: `/static/icon_${item.type}.png`,
    })),
  });
  // 缩放地图已展示出所有的标注点
  mapCtx?.includePoints({
    points: (data as API.Trade[]).map((item) => ({
      longitude: +item.lng,
      latitude: +item.lat,
    })),
    padding: [50, 50, 50, 50],
  });
};

// 标注点点击
const handleMarkerTap = (event: any) => {
  // 获取标注点Id
  const { markerId } = event;
  // 跳转页面
  uni.navigateTo({
    url: "/pages/info/info?id=" + markerId,
  });
};

// 跳转发布
const handleJump = () => {
  uni.navigateTo({
    url: "/pages/publish/publish",
    events: {
      refresh: () => {
        console.log("index refresh");
        // 重新获取下数据
        refresh();
      },
    },
  });
};

onLoad(() => {
  mapCtx = uni.createMapContext("map");

  refresh();
});
</script>

<style lang="scss">
page {
  height: 100%;
}

#map {
  width: 100%;
  height: 100%;
}

.footer {
  position: fixed;
  left: 0;
  bottom: 0;

  width: 100%;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  background-color: #fff;
}
</style>
